package com.ly.user_system.filter;

import com.ly.user_system.common.CommonConstant;
import com.ly.user_system.utils.UserContextUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * @author HASEE
 */
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private JwtDecoder jwtDecoder;

    private UserDetailsService userDetailsService;

    private RequestMatcher whiteUrlMatcher;

    public JwtAuthenticationFilter(JwtDecoder jwtDecoder, UserDetailsService userDetailsService, RequestMatcher whiteUrlMatcher) {
        this.jwtDecoder = jwtDecoder;
        this.userDetailsService = userDetailsService;
        this.whiteUrlMatcher = whiteUrlMatcher;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 白名单放行
            if (whiteUrlMatcher.matches(request)){
            filterChain.doFilter(request,response);
            return;
        }
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        try{
            Jwt decode = jwtDecoder.decode(token);
            String userName = decode.getClaimAsString(CommonConstant.JWT_USER_NAME);
            UserDetails userDetails = userDetailsService.loadUserByUsername(userName);
            UserContextUtil.setUserContext(new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities()));
        }catch (Exception e){
            logger.info("occur error:"+e.getMessage());
            return;
        }
        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {
        super.destroy();
        UserContextUtil.clear();
    }
}
